package com.leyou.search.service;

import com.fasterxml.jackson.core.type.TypeReference;
import com.item.dto.*;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.JsonUtils;
import com.leyou.item.client.ItemClient;
import com.leyou.search.pojo.Goods;
import com.leyou.search.repository.GoodsRepository;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class IndexService {

//    跨服务调用的ctroller
    @Autowired
    private ItemClient itemClient;


    @Autowired
    private GoodsRepository goodsRepository;

//    spuDTO和goods结构相同
    public Goods buildGoods(SpuDTO spuDTO){
//        spuDTO转成goods对象
        Goods goods = BeanHelper.copyProperties(spuDTO, Goods.class);

        /**
         *  "skus": null,
         "all": null,
         "categoryId": null,
         "createTime": null,
         "price": null,
         "specs": null
         */
//        "categoryId": null,
//         "createTime": null,
        goods.setCreateTime(spuDTO.getCreateTime().getTime());
        goods.setCategoryId(spuDTO.getCid3());

//        "all": null,
//
        String names = this.itemClient.queryByIds(spuDTO.getCategoryIds())
                .stream()
//                获取名字并以空格来拼成字符串
                .map(CategoryDTO::getName).collect(Collectors.joining(" "));

//        给all属性添加内容
        goods.setAll(spuDTO.getName()+" " + names);

//        "skus": null,
//        sku:有很多属性，只要四个：id price image title (流量贵)
//        拿到所有的skuDTO对象
        List<SkuDTO> skuDTOList = this.itemClient.querySkuBySpuId(spuDTO.getId());

//        创建一个集合用来保存数据
        List<Map<String,Object>> skuList = new ArrayList<>();

//        存放price属性
        Set<Long> prices = new HashSet<>();

//        遍历所有skuDTO对象存放到map并添加到list集合中
        skuDTOList.forEach(skuDTO -> {

//            添加price属性
            prices.add(skuDTO.getPrice());

            HashMap<String, Object> map = new HashMap<>();
            map.put("id",skuDTO.getId());
            map.put("price",skuDTO.getPrice());
            map.put("image",skuDTO.getImages().split(",")[0]);
            map.put("title",skuDTO.getTitle());

            skuList.add(map);



        });


//      添加skus
        goods.setSkus(JsonUtils.toString(skuList));
//       添加prices属性
        goods.setPrice(prices);

        /**
         * "specs": null
         */
//        根据分类查询可搜索的规格参数
        List<SpecParamDTO> specParamDTOS = this.itemClient.querySpecParams(null, spuDTO.getCid3(), true);

        Map<String, Object> specs = new HashMap<>();

//        根据spuID查询spuDetail
        SpuDetailDTO spuDetailDTO = this.itemClient.querySpuDetailById(spuDTO.getId());
//        JsonUtils.nativeRead():string到json
//       查询通用规格
        Map<Long, Object> genericMap = JsonUtils.nativeRead(spuDetailDTO.getGenericSpec(), new TypeReference<Map<Long, Object>>() {
        });

        //       查询特有规格
        Map<Long,List<String>> specailMap = JsonUtils.nativeRead(spuDetailDTO.getSpecialSpec(), new TypeReference<Map<Long, List<String>>>() {
        });


//        遍历
        specParamDTOS.forEach(specParamDTO -> {
//            规格参数的id
            Long id = specParamDTO.getId();

            String name = specParamDTO.getName();

            Object value;
            if (specParamDTO.getGeneric()){//通用从通用规格中取值
                value = genericMap.get(id);
            }else{//特有从特有规格中取值
                value = specailMap.get(id);
            }

            // 判断是否是数值类型
            if(specParamDTO.getNumeric()){
                // 是数字类型，分段
                value = chooseSegment(value, specParamDTO);
            }

            specs.put(name,value);



        });

        goods.setSpecs(specs);
        return goods;
    }

    //  显示数字区间
    private String chooseSegment(Object value, SpecParamDTO p) {
        if (value == null || StringUtils.isBlank(value.toString())) {
            return "其它";
        }
        double val = parseDouble(value.toString());
        String result = "其它";
        // 保存数值段
        for (String segment : p.getSegments().split(",")) {
            String[] segs = segment.split("-");
            // 获取数值范围
            double begin = parseDouble(segs[0]);
            double end = Double.MAX_VALUE;
            if (segs.length == 2) {
                end = parseDouble(segs[1]);
            }
            // 判断是否在范围内
            if (val >= begin && val < end) {
                if (segs.length == 1) {
                    result = segs[0] + p.getUnit() + "以上";
                } else if (begin == 0) {
                    result = segs[1] + p.getUnit() + "以下";
                } else {
                    result = segment + p.getUnit();
                }
                break;
            }
        }
        return result;
    }

        private double parseDouble(String str) {
            try {
                return Double.parseDouble(str);
            } catch (Exception e) {
                return 0;
            }
        }

    public void createItemHtml(Long id) {

        SpuDTO spuDTO = this.itemClient.querySpuById(id);
        Goods goods = buildGoods(spuDTO);
        this.goodsRepository.save(goods);

    }

    public void deleteItemHtml(Long id) {
        this.goodsRepository.deleteById(id);
    }
}
